package com.itheima.text;

import com.itheima.bean.Student;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.Set;

@WebServlet(urlPatterns = "/addStudentServlet")
public class AddStudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        //获取参数
        Map<String, String[]> pm = req.getParameterMap();

        Set<String> names = pm.keySet();
        //封装学生对象
        Student stu = new Student();

//        BeanMap beanMap = new BeanMap();
        try {
            BeanUtils.populate(stu,pm);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //把学生对象存储到文件中
        BufferedWriter bw = new BufferedWriter(new FileWriter(getServletContext().getRealPath("/")+"\\stu.txt",true));
        bw.write(stu.getUsername()+","+stu.getAge()+","+stu.getScore());
        bw.newLine();
        bw.close();

        //显示添加成功信息，并跳转到首页
        resp.setContentType("com.itheima.text/html;charset=UTF-8");

        PrintWriter pw = resp.getWriter();
        pw.write("添加成功，2秒中后跳转到首页。。。");

        resp.setHeader("Refresh","2;URL=/day4/index.jsp");




    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
